package com.yhhl.balance;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.log4j.Logger;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.yhhl.common.ZkClientManageImpl;
import com.yhhl.common.IZkClientConfigManage;

public class Launch {

	private final static Logger log = Logger.getLogger(Launch.class);

	public static final String SHUTDOWN_HOOK_KEY = "server.shutdown.hook";
	private static volatile boolean running = true;

	private static IZkClientConfigManage configManage;

	public static void main(String[] args) {
		long l = System.currentTimeMillis();
		ClassPathXmlApplicationContext context = null;
		try {
			log.info(Launch.class.getName() + " 初始化...");
			context = new ClassPathXmlApplicationContext(new String[] { "classpath:applicationContext.xml" });
			final ClassPathXmlApplicationContext ctx = context;
			if ("true".equals(System.getProperty(SHUTDOWN_HOOK_KEY))) {
				Runtime.getRuntime().addShutdownHook(new Thread() {

					@Override
					public void run() {
						try {
							ctx.stop();
							log.warn("服务关闭！");
						} catch (Exception e) {
							log.error(e.getMessage(), e);
						} catch (Throwable t) {
							log.error(t.getMessage());
						}
						synchronized (Launch.class) {
							running = false;
							Launch.class.notify();
						}
						super.run();
					}

				});
			}

			// 拉起服务
			context.start();
			log.info(Launch.class.getName() + " 启动结束，用时：" + (System.currentTimeMillis() - l) + " ms");
			configManage = (ZkClientManageImpl) context.getBean("configManage");
			// 测试 Zookeeper的添加和获取
			Map<String, String> map = configManage.getAll();
			show(map);
			try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in,"UTF-8"));) {
				String str = null;
				String[] ary = null;
				while ((str = br.readLine()) != null && !str.equals("quit")) {
					ary = str.split(" ");
					
					if(ary[2].equals("get")){
						map = configManage.getAll();
					}else if(ary[2].equals("del")){
						configManage.delete(ary[0]);
						map = configManage.getAll();
					}else{
						String value = configManage.get(ary[0]);
						if(value==null || "".equals(value)){
							configManage.add(ary[0], ary[1]);
						}else{
							configManage.update(ary[0], ary[1]);
						}
						map = configManage.getAll();
					}
					
					show(map);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		} catch (RuntimeException e) {
			log.error(e.getMessage(), e);
			if (context != null) {
				context.stop();
			}
		}
		synchronized (Launch.class) {
			while (running) {
				try {
					Launch.class.wait();
				} catch (Throwable e) {
					// e.printStackTrace();
				}
			}
		}

	}
	
	private static void show(Map<String,String> map){
		Set<Entry<String, String>> set = map.entrySet();
		Iterator<Entry<String,String>> itr = set.iterator();
		while(itr.hasNext()){
			Entry<String,String> entry = itr.next();
			System.out.println(entry.getKey()+"："+entry.getValue());
		}
	}

}
